package com.cheng.testnetwork.network;

import com.cheng.testnetwork.util.LogUtil;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Retrofit;

/**
 * Created by cheng on 2017/11/28.
 * 同步下载
 */
public class HttpSyncDownManager {

    /**
     * 单利对象
     */
    private volatile static HttpSyncDownManager INSTANCE;

    /**
     * 超时时间，单位为秒
     */
    private int timeout = 30;

    private Call<ResponseBody> call;

    private HttpSyncDownManager() {
    }

    /**
     * 获取单例
     *
     * @return
     */
    public static HttpSyncDownManager getInstance() {
        if (INSTANCE == null) {
            synchronized (HttpSyncDownManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new HttpSyncDownManager();
                }
            }
        }
        return INSTANCE;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    /**
     * 开始下载
     */
    public void startDown(DownInfo info) {

        /*获取service，多次请求公用一个sercie*/
        HttpService httpService;

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //手动创建一个OkHttpClient并设置超时时间
        builder.connectTimeout(timeout, TimeUnit.SECONDS);

        Retrofit retrofit = new Retrofit.Builder()
                .client(builder.build())
                .baseUrl(info.getBaseUrl())
                .build();
        httpService = retrofit.create(HttpService.class);

        call = httpService.download(info.getUrl());
        LogUtil.d("开始下载,下载info\n"+info);
        /*得到rx对象-上一次下載的位置開始下載*/
        try {
            writeCache(call.execute().body(),new File(info.getSavePath()),info);
        } catch (Exception e) {
            LogUtil.e(e);
        }
        LogUtil.d("完成下载");
        call = null;
    }


    /**
     * 停止下载
     */
    public void stopDown() {

        if (call != null && !call.isCanceled()){
            try {
                call.cancel();
                if (call.isCanceled()) {
                    LogUtil.d("下载已经停止");
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 写入文件
     *
     * @param file
     * @param info
     * @throws IOException
     */
    public void writeCache(ResponseBody responseBody, File file, DownInfo info) throws IOException {
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        long allLength;
        if (info.getCountLength() == 0) {
            allLength = responseBody.contentLength();
        } else {
            allLength = info.getCountLength();
        }

        FileChannel channelOut = null;
        RandomAccessFile randomAccessFile = null;
        randomAccessFile = new RandomAccessFile(file, "rwd");
        channelOut = randomAccessFile.getChannel();
        MappedByteBuffer mappedBuffer = channelOut.map(FileChannel.MapMode.READ_WRITE,
                info.getReadLength(), allLength - info.getReadLength());
        byte[] buffer = new byte[1024 * 16];
        int len;
        int record = 0;
        while ((len = responseBody.byteStream().read(buffer)) != -1) {
            mappedBuffer.put(buffer, 0, len);
            record += len;
            System.out.println(record);
        }
        LogUtil.e(record + "====" + allLength);

        responseBody.byteStream().close();
        channelOut.close();
        randomAccessFile.close();

    }


}
